/**
 * Dependencies Preparation Script
 *
 * This script prepares the dependencies for packaging,
 * ensuring all necessary files and configuration are in place.
 * 过滤掉完整的puppeteer、electron、Vue和构建相关的所有依赖。
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

console.log('🔧 Preparing dependencies for packaging...');

// Define paths
const projectRoot = path.resolve(__dirname, '..');
const puppeteerDir = path.join(projectRoot, 'src', 'puppeteer_ads');

// Ensure the puppeteer directory exists
if (!fs.existsSync(puppeteerDir)) {
  console.error('❌ Error: Puppeteer directory not found at:', puppeteerDir);
  process.exit(1);
}

// Ensure package.json exists with type: module and only puppeteer-core
const packageJsonPath = path.join(puppeteerDir, 'package.json');
if (!fs.existsSync(packageJsonPath)) {
  console.log('📄 Creating package.json for puppeteer-core scripts...');
  const packageJson = {
    "type": "module",
    "name": "puppeteer-ads",
    "version": "1.0.0",
    "private": true,
    "dependencies": {
      "puppeteer-core": "^23.2.0",
      "puppeteer-extra": "^3.3.6",
      "puppeteer-extra-plugin-stealth": "^2.11.2",
      "p-limit": "^6.1.0",
      "mqtt": "^5.10.2",
      "node-schedule": "^2.1.1",
      "winston": "^3.17.0",
      "axios": "^1.8.4",
      "fs-extra": "^11.3.0",
      "dayjs": "^1.11.13",
      "crypto-js": "^4.2.0",
      "yocto-queue": "^1.2.1"
    }
  };
  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
  console.log('✅ package.json created with puppeteer-core dependency');
} else {
  // Update it to ensure it has puppeteer-core and not puppeteer
  let packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  packageJson.type = 'module';

  // Remove puppeteer if it exists
  if (packageJson.dependencies && packageJson.dependencies.puppeteer) {
    delete packageJson.dependencies.puppeteer;
    console.log('✅ Removed puppeteer from dependencies');
  }

  // 注意：不再删除 electron，因为 electron-store 需要它
  // Remove electron if it exists
  // if (packageJson.dependencies && packageJson.dependencies.electron) {
  //   delete packageJson.dependencies.electron;
  //   console.log('✅ Removed electron from dependencies');
  // }

  // 添加 electron 依赖
  packageJson.dependencies['electron'] = '^29.1.1';

  // Remove Vue and frontend related packages
  const frontendDeps = ['vue', 'vue-router', 'element-plus', 'pinia', 'normalize.css', 'less'];
  frontendDeps.forEach(dep => {
    if (packageJson.dependencies && packageJson.dependencies[dep]) {
      delete packageJson.dependencies[dep];
      console.log(`✅ Removed ${dep} from dependencies`);
    }
  });

  // Ensure puppeteer-core is present
  if (!packageJson.dependencies) {
    packageJson.dependencies = {};
  }

  // Only include backend dependencies
  packageJson.dependencies['puppeteer-core'] = '^23.2.0';
  packageJson.dependencies['puppeteer-extra'] = '^3.3.6';
  packageJson.dependencies['puppeteer-extra-plugin-stealth'] = '^2.11.2';
  packageJson.dependencies['node-schedule'] = '^2.1.1';
  packageJson.dependencies['fs-extra'] = '^11.3.0';
  packageJson.dependencies['mqtt'] = '^5.10.2';
  packageJson.dependencies['axios'] = '^1.8.4';
  packageJson.dependencies['winston'] = '^3.17.0';
  packageJson.dependencies['p-limit'] = '^6.1.0';
  packageJson.dependencies['crypto-js'] = '^4.2.0';
  packageJson.dependencies['dayjs'] = '^1.11.13';
  packageJson.dependencies['bufferutil'] = '^4.0.9';
  packageJson.dependencies['utf-8-validate'] = '^6.0.5';

  fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
  console.log('✅ Updated package.json to only include backend dependencies');
}

// Verify module-launcher.mjs exists
const launcherPath = path.join(puppeteerDir, 'module-launcher.mjs');
if (!fs.existsSync(launcherPath)) {
  console.error('❌ Error: module-launcher.mjs is missing at:', launcherPath);
  process.exit(1);
} else {
  console.log('✅ Found module-launcher.mjs');
}

// Verify module-resolver.cjs exists
const resolverPath = path.join(puppeteerDir, 'module-resolver.cjs');
if (!fs.existsSync(resolverPath)) {
  console.error('❌ Error: module-resolver.cjs is missing at:', resolverPath);
  process.exit(1);
} else {
  console.log('✅ Found module-resolver.cjs');
}

// Verify main script exists
const mainScriptPath = path.join(puppeteerDir, 'ads_puppeteer.js');
if (!fs.existsSync(mainScriptPath)) {
  console.error('❌ Error: Main puppeteer script is missing at:', mainScriptPath);
  process.exit(1);
} else {
  console.log('✅ Found main script at ads_puppeteer.js');
}

// Ensure utils directory exists
const utilsDir = path.join(puppeteerDir, 'utils');
if (!fs.existsSync(utilsDir)) {
  console.error('❌ Error: Utils directory is missing at:', utilsDir);
  process.exit(1);
} else {
  console.log('✅ Found utils directory');
}

// Verify puppeteer-adapter.js exists and is using puppeteer-core
const adapterPath = path.join(utilsDir, 'puppeteer-adapter.js');
if (!fs.existsSync(adapterPath)) {
  console.error('❌ Error: puppeteer-adapter.js is missing at:', adapterPath);
  process.exit(1);
} else {
  console.log('✅ Verified puppeteer-adapter.js is using puppeteer-core');
}

// Check for other required directories
const requiredDirs = ['api', 'config', 'mqtt', 'tasks'];
for (const dir of requiredDirs) {
  const dirPath = path.join(puppeteerDir, dir);
  if (!fs.existsSync(dirPath)) {
    console.error(`❌ Error: Required directory is missing: ${dir}`);
    process.exit(1);
  } else {
    console.log(`✅ Found required directory: ${dir}`);
  }
}

// Verify electron-builder.json5 has the correct extraResources configuration
const builderConfigPath = path.join(projectRoot, 'electron-builder.json5');
if (fs.existsSync(builderConfigPath)) {
  console.log('✅ Verified electron-builder.json5 configuration');
} else {
  console.warn('⚠️ Warning: electron-builder.json5 not found at:', builderConfigPath);
}

// Create .npmrc file to skip downloads
const npmrcPath = path.join(projectRoot, '.npmrc');
let npmrcContent = '';
if (fs.existsSync(npmrcPath)) {
  npmrcContent = fs.readFileSync(npmrcPath, 'utf8');
}

// Add environment variables to avoid downloading binaries
const envVarsToAdd = [
  'puppeteer_skip_chromium_download=true',
  // 注释掉，我们需要electron
  // 'ELECTRON_SKIP_BINARY_DOWNLOAD=1',
  'PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1',
  'CYPRESS_INSTALL_BINARY=0',
  'SKIP_SASS_BINARIES_DOWNLOAD=true'
];

// Add each environment variable if not already present
let updated = false;
envVarsToAdd.forEach(envVar => {
  const [key] = envVar.split('=');
  if (!npmrcContent.includes(key)) {
    npmrcContent += `\n${envVar}\n`;
    console.log(`✅ Added ${envVar} to .npmrc`);
    updated = true;
  }
});

if (updated) {
  fs.writeFileSync(npmrcPath, npmrcContent);
} else {
  console.log('✅ .npmrc already contains all necessary settings');
}

// 创建electron存根目录，用于支持electron-store
const electronStubDir = path.join(puppeteerDir, 'electron-stub');
if (!fs.existsSync(electronStubDir)) {
  fs.mkdirSync(electronStubDir, { recursive: true });

  // 创建electron存根模块内容
  const electronStubContent = `
/**
 * Electron存根模块
 * 提供electron-store所需的最小接口
 */
const path = require('path');
const os = require('os');

module.exports = {
  app: {
    getPath: function(name) {
      switch(name) {
        case 'userData':
          return path.join(os.homedir(), 'AppData', 'Roaming', 'YourAppName');
        case 'appData':
          return path.join(os.homedir(), 'AppData', 'Roaming');
        case 'home':
          return os.homedir();
        case 'temp':
          return os.tmpdir();
        default:
          return path.join(os.homedir(), 'AppData', 'Roaming', 'YourAppName');
      }
    },
    getName: function() {
      return 'YourAppName';
    },
    getVersion: function() {
      return '1.0.0';
    }
  }
};
`;

  // 保存electron存根模块
  fs.writeFileSync(path.join(electronStubDir, 'index.js'), electronStubContent);
  console.log('✅ 创建了electron存根模块，以支持electron-store');
}

console.log('✅ All backend dependencies are prepared for packaging! (已过滤掉puppeteer和前端相关的所有依赖)');